<template>
    <div class="page">
        <!-- <el-dialog title="提示" :visible.sync="dialogVisible" width="866px" top="50px" :close-on-click-modal="false">
            <div class="dialog-text">建议使用谷歌浏览器，如不显示地图，建议更改MTU值为1400。</div>
            <div class="dialog-text">MTU设置方式：网络-有线链接-配置-以太网-自定义MTU-手动输入“1400”-保存。</div>
            <img src="../../assets/img//mtu.png" class="mtu-img" />
            <span slot="footer" class="dialog-footer">
                <el-checkbox v-model="checked" class="dialog-checked">不再提示</el-checkbox>
                <el-button type="primary" @click="isHide">确 定</el-button>
            </span>
        </el-dialog> -->
        <!-- <el-button type="primary" class="go-open-btn" @click="goWinOpen">去办理</el-button> -->
        <!-- <div class="header">
            作战地图
        </div> -->
        <!-- <leftComponent/> -->
        <div class="show-btn" :style="detail || shopDetail ? showLeft ? {} : { left: 0 } : { left: '-100px' }"
            @click="showPanel('Left')">
            <i class="el-icon-d-arrow-left" v-if="showLeft"></i>
            <i class="el-icon-d-arrow-right" v-else></i>
        </div>
        <div class="show-btn"
            :style="!(detail || shopDetail) ? showNum ? { left: '360px' } : { left: 0 } : { left: '-100px' }"
            v-show="searchType != '1' && haveIndicator" @click="showPanel('Num')">
            <i class="el-icon-d-arrow-left" v-if="showNum"></i>
            <i class="el-icon-d-arrow-right" v-else></i>
        </div>
        <numLeft v-show="showNum && !(detail || shopDetail) && searchType != '1' && haveIndicator" :numObj="numObj"
            ref="numRef" />
        <communityLeft v-if="detail && showLeft && searchType != '1'" :detail="detail" :date="date"
            :haveIndicator="haveIndicator" />
        <shopLeft v-if="shopDetail && showLeft && searchType == '1'" :detail="shopDetail" />
        <!-- <div class="noDrew" @click="isDrew = true" v-if="!isDrew">
            <img src="@/assets/img/icon7.png" />
            <div class="text">绘制</div>
        </div> -->
        <!-- <div class="isDrew" @click="clear" v-else>
            <img src="@/assets/img/icon6.png" />
            <div class="text">绘制</div>
        </div>
        <div class="drew" v-if="isDrew">
            <div class="drew-item" @click="drewTool('0')" :class="drew === '0' ? 'drew-item-active' : ''">
                <img src="@/assets/img/icon1.png" />
                <div class="drew-btn">圆形</div>
            </div>
            <div class="drew-item" @click="drewTool('1')" :class="drew === '1' ? 'drew-item-active' : ''">
                <img src="@/assets/img/icon2.png" />
                <div class="drew-btn">方形</div>
            </div>
            <div class="drew-item" @click="drewTool('2')" :class="drew === '2' ? 'drew-item-active' : ''">
                <img src="@/assets/img/icon3.png" />
                <div class="drew-btn">自定义</div>
            </div>
            <div class="drew-item" @click="isOk">
                <img src="@/assets/img/icon4.png" />
                <div class="drew-btn">确定</div>
            </div>
            <div class="drew-item" @click="clear">
                <img src="@/assets/img/icon5.png" />
                <div class="drew-btn">取消</div>
            </div>
        </div> -->
        <div class="isDrag" :class="isDrag ? 'isDrag-bg' : ''" @click="setDrag"
            :style="detail || shopDetail ? showLeft ? (getHaveDrag() ? {} : { display: 'none' }) : { left: '10px' } : { display: 'none' }">
            <img :src="isDrag ? require('@/assets/img/drag1.png') : require('@/assets/img/drag.png')" />
            <div class="text">拖拽</div>
        </div>
        <div class="drag-box" v-if="isDrag" :style="showLeft ? {} : { left: '80px' }">
            <div class="drew-item" @click="getSave(false)">
                <img src="@/assets/img/ok.png" />
                <div class="drew-btn">确定</div>
            </div>
            <div class="drew-item" @click="getClose(true)">
                <img src="@/assets/img/close.png" />
                <div class="drew-btn">取消</div>
            </div>
        </div>
        <div class="noDrew" :style="showLeft ? { left: '580px' } : { left: '230px' }" slot="reference"
            v-if="isDrag && isSave" @click="getSave(true)">
            <img src="@/assets/img/save.png" />
            <div class="text">保存</div>
        </div>
        <!-- <el-popover placement="bottom" width="90" trigger="click" class="popover-box">
            <div class="noDrew" :style="{ left: isDrew ? '750px' : '390px' }" slot="reference">
                <img src="@/assets/img/icon8.png" />
                <div class="text">我的绘制</div>
            </div>
            <el-checkbox-group v-model="checkList">
                <el-checkbox label="图层1"></el-checkbox>
                <el-checkbox label="图层2"></el-checkbox>
                <el-checkbox label="图层3"></el-checkbox>
            </el-checkbox-group>
        </el-popover> -->
        <div id="map"></div>
        <!-- <div class="list-box" v-if="isTypeList">
            <i class="el-icon-close" @click="isTypeList = false"></i>
            <div class="list-box-inset">
                <div class="list-item" v-for="i in 8">
                    <img src="@/assets/img/test.png" />
                    <div>
                        <div class="title">晓江南南菜馆</div>
                        <div class="address" title="南岗区凯德广场五楼">地址：南岗区凯德广场五楼</div>
                        <div class="phone">电话：18518355380</div>
                    </div>
                </div>
            </div>
        </div> -->
        <div class="type-box" v-if="detail || shopDetail || (searchType == '1' && (value2 || searchValue))"
            :style="showRight ? {} : { right: '10px' }">
            <!-- <div class="type-item" v-for="item, i in typeList" :key="i" @click="showPoint(i)">
                <span>{{ item.name }}</span>
                <img :src="require(`@/assets/img/type${i + 1}.png`)" />
            </div> -->
            <div class="right-title" style="left: 14; right:auto; top: 15px;">打点类型</div>
            <div class="check-box">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                    @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="checkedTypes" @change="handleCheckedTypesChange">
                    <el-checkbox v-for="type in types" :label="type" :key="type">
                        {{ type }}
                        <img src="@/assets/img/build.png" v-if="type == '楼栋'" class="rignt-icon" />
                        <img src="@/assets/img/point.png" v-if="type == '单元'" class="rignt-icon"
                            style="width: 12px; margin: 5px 4px;" />
                        <img src="@/assets/img/shop.png" v-if="type == '商铺'" class="rignt-icon" />
                    </el-checkbox>
                </el-checkbox-group>
            </div>
        </div>
        <div class="show-btn-right" :style="showRight ? {} : { right: 0 }" @click="showPanel('Right')">
            <i class="el-icon-d-arrow-right" v-if="showRight"></i>
            <i class="el-icon-d-arrow-left" v-else></i>
        </div>
        <div class="right-box" v-if="showRight">
            <notice-bar v-if="dialogVisible"
                text="建议使用谷歌浏览器，如不显示地图，建议更改MTU值为1400。MTU设置方式：网络-有线链接-配置-以太网-自定义MTU-手动输入“1400”-保存。" @click="isHide" />
            <div class="right-top-box">
                <el-date-picker v-model="date" type="date" placeholder="选择日期" class="picker-box min-picker"
                    :picker-options="setDisabled" @change="getDateDetail" format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"></el-date-picker>
                <div class="longin-name">
                    <span class="longin-text">登录人</span>
                    <span class="name-text" :title="userInfo.userName || '--'">{{ userInfo.userName || '--' }}</span>
                </div>
            </div>
            <div class="right-bottom-box">
                <div class="right-title" :class="fgqFgShow && 'pointer'">小区清单</div>
                <div class="go-back-btn" v-if="choiceMark" @click="hideList">
                    返回
                </div>
                <div class="search-title"
                    :class="choiceMark || !isSearch || showDyList || fgqFgShow ? 'search-title-radius' : ''">
                    <el-select v-model="searchType" v-if="!choiceMark && isSearch && !showDyList && !fgqFgShow"
                        @change="changeType">
                        <el-option label="搜小区" value="0"></el-option>
                        <!-- <el-option label="搜商铺" value="1"></el-option>  -->
                        <el-option label="搜位置" value="2"></el-option>
                    </el-select>
                    <div @click="goSearch" v-else>{{ searchType == '0' ? '搜小区' : searchType == '1' ? '搜商铺' : '搜位置' }}<i
                            class="el-icon-arrow-down"></i>
                    </div>
                </div>
                <div class="all-list" v-loading="loading" :style="dialogVisible ? { height: 'calc(100% - 95px)' } : {}">
                    <div class="all-list-item" v-for="item, i in communityList" @click="setMapCenter(item)">
                        <div class="item-name">{{ getName(item.communityName) }}</div>
                        <el-tag type="warning" color="#fafbf2" v-if="item.sfxxq == '是'">10GPON小区</el-tag>
                        <div class="item-value">
                            <span class="name">地址:</span>
                            {{ item.communityName }}
                        </div>
                    </div>
                    <el-pagination v-if="communityList.length" @current-change="handleCurrentChange" :pager-count="5"
                        class="pagination" :current-page="currentPage" :page-size="9"
                        layout="total, prev, pager, next, jumper" :total="communityTotal">
                    </el-pagination>
                </div>
                <div class="search-list-box" v-if="!choiceMark && isSearch && !showDyList">
                    <div class="hide-search" @click="hideSearch">
                        <img src="@/assets/img/hide.png" />收起
                    </div>
                    <div class="search-area">
                        <el-select v-model="value" slot="prepend" placeholder="请选择" @change="changeCity" clearable
                            :disabled="userLevel == '2' || userLevel == '3' || userLevel == '4'">
                            <el-option v-for="item in options" :key="item.orgId" :label="item.name" :value="item.orgId">
                            </el-option>
                        </el-select>
                        <el-select v-model="value1" slot="prepend" placeholder="请选择" @change="changeDistrict" clearable
                            :disabled="userLevel == '3' || userLevel == '4'">
                            <el-option v-for="item in optionsQx" :key="item.orgId" :label="item.name"
                                :value="item.orgId">
                            </el-option>
                        </el-select>
                        <el-select v-model="value2" slot="prepend" placeholder="请选择" clearable @change="changeWg"
                            :disabled="userLevel == '4'">
                            <el-option v-for="item in optionsWg" :key="item.orgId" :label="item.name"
                                :value="item.orgId">
                            </el-option>
                        </el-select>
                    </div>
                    <el-input placeholder="请输入内容" v-model="search" class="search-value"
                        @keyup.enter.native="startSearch">
                        <el-button slot="append" icon="el-icon-search" @click="startSearch"></el-button>
                    </el-input>
                    <div class="search-list" v-loading="loading" v-if="listShow"
                        :style="dialogVisible ? { height: 'calc(100% - 126px)' } : {}">
                        <div class="search-content" v-if="searchValue">
                            <img src="@/assets/img/search-icon.png" />
                            <span>{{ searchValue }}</span>
                        </div>
                        <div class="search-item" v-for="item, i in searchList" :key="i" @click="setMapCenter(item)">
                            <img src="@/assets/img/searchIcon.png" />
                            <span class="name" :title="getName(item.communityName)">{{
                                getName(item.communityName) }}</span>
                            <span class="address" :title="item.cityName + item.countyName + item.gridName">
                                {{ item.cityName + item.countyName + item.gridName }}</span>
                            <span class="len">{{ getdistance(item.distance) }}KM</span>
                        </div>
                        <div class="empty-box" v-if="!searchList.length">
                            <img src="@/assets/img/empty.png" />
                            <div class="empty-text">暂无数据</div>
                        </div>
                    </div>
                    <div class="search-list" v-loading="shopLoading" v-if="shopListShow"
                        :style="dialogVisible ? { height: 'calc(100% - 126px)' } : {}">
                        <div class="search-content" v-if="searchValue">
                            <img src="@/assets/img/search-icon.png" />
                            <span>{{ searchValue }}</span>
                        </div>
                        <div class="search-item" v-for="item, i in shopList" :key="i" @click="setMapCenter(item)">
                            <img src="@/assets/img/searchIcon.png" />
                            <span class="name name-max" :title="item.shopName">{{ item.shopName }}</span>
                            <span class="address" :title="item.cityName + item.countyName + item.gridName">
                                {{ item.cityName + item.countyName + item.gridName }}</span>
                        </div>
                        <div class="empty-box" v-if="!shopList.length">
                            <img src="@/assets/img/empty.png" />
                            <div class="empty-text">暂无数据</div>
                        </div>
                    </div>
                </div>
                <div class="ld-list" v-if="showDyList" :style="dialogVisible ? { height: 'calc(100% - 100px)' } : {}">
                    <div class="ld-item" v-for="item, i in dyList" :key="i" @click="setDyCenter(item)">
                        <div class="ld-name">{{ item.title }}</div>
                    </div>
                    <div class="empty-box" v-if="!dyList.length">
                        <img src="@/assets/img/empty.png" />
                        <div class="empty-text">暂无数据</div>
                    </div>
                </div>
                <div class="fgq-list" v-if="fgqFgShow">
                    <i class="el-icon-close" @click="hideFgq()"></i>
                    <div class="fgq-title">{{ fgqFg.addressName + '|' + fgqFg.buildingName + '|' + fgqFg.unitName + '|'
                        + (fgqFg.oltVendorName || '') }}</div>
                    <div class="fgq-item" v-for="val, idx in fgqFg.fiberConverterList" :key="idx">
                        <div class="fgq-name">
                            <div class="community-fgq">
                                <div class="community-fgq-text" @dblclick="goCopyText(val.fiberConverterStr)">{{
                                    val.fiberConverterStr }}</div>
                                <span class="copy-text-btn" @click="goWinOpen(val, fgqFg)">去办理</span>
                            </div>
                            <div>建设端口:{{ val.addDk || 0 }}个 实占端口:{{ val.szDk || 0 }}个 预占端口:{{ val.yzDk || 0 }}个 空闲端口:{{
                                val.addDk - val.szDk }}个</div>
                        </div>
                    </div>
                    <div class="empty-box" v-if="!fgqFg.fiberConverterList.length">
                        <img src="@/assets/img/empty.png" />
                        <div class="empty-text">暂无数据</div>
                    </div>
                </div>
                <div class="community-list" v-if="choiceMark" v-loading="loading"
                    :style="dialogVisible ? { height: 'calc(100% - 105px)' } : {}">
                    <div class="community-item" v-for="item, i in fgqList" :key="i">
                        <div class="community-name" @click="showFgqFg(item)">{{ item.addressName + '|' +
                            item.buildingName + '|' + item.unitName + '|' + (item.oltVendorName || '') }}
                        </div>
                        <div class="community-fgq" v-for="val, idx in item.fiberConverterList" :key="idx">
                            <div class="community-fgq-text" @dblclick="goCopyText(val.fiberConverterStr)">{{
                                val.fiberConverterStr }}</div> <span class="copy-text-btn"
                                @click="goWinOpen(val, item)">去办理</span>
                        </div>
                    </div>
                    <el-pagination v-if="fgqList.length" @current-change="handleCurrentChange1" :pager-count="5"
                        class="pagination" :current-page="currentPage1" :page-size="4"
                        layout="total, prev, pager, next, jumper" :total="fgqTotal">
                    </el-pagination>
                    <div class="empty-box" v-else>
                        <img src="@/assets/img/empty.png" />
                        <div class="empty-text">暂无数据</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import build from '@/assets/img/build.png'
import shop from '@/assets/img/shop.png'
import point from '@/assets/img/point.png'
import point1 from '@/assets/img/point1.png'
import communityLeft from './components/communityLeft.vue'
import numLeft from './components/numLeft.vue'
import shopLeft from './components/shopLeft.vue'
import leftComponent from './components/leftComponent.vue'
import communityRight from './components/communityRight.vue'
import moment from 'moment'
import addressActive from '@/assets/img/address-active.png'
import WKT from 'terraformer-wkt-parser'
import * as turf from '@turf/turf';
import NoticeBar from './components/NoticeBar'
import { getInfo, getUserLocation, getCommunityDetail, getPlaceLocation, getOrgList, getAllList, getNumList, getFgq, editCommunity, editBuildings, editUnits, editShops, getDate, searchShopList, getShopDetail, getShopUints, shopsNearBuildingList } from '@/api/api'
let gridSize = 60
// 数据中需包含经纬度信息字段 lnglat
let points = []
let count = points.length;
let cluster;
let editor = null
let polygonData = null;
let pointLdData = null;
let pointDyData = null;
let pointDpData = null;
let polygonCenter = null;
export default {
    name: 'mapCenter',
    components: {
        communityLeft,
        communityRight,
        leftComponent,
        shopLeft,
        NoticeBar,
        numLeft
    },
    data() {
        return {
            userLevel: '2',
            areaType: 'MultiPolygon',
            numObj: {},
            checked: false,
            dialogVisible: false,
            shopListShow: false,
            listShow: true,
            newMark: null,
            oldShopDetail: {},
            shopDetail: null,
            oldDetail: {},
            showDyList: false,
            loading: false,
            shopLoading: false,
            userInfo: {},
            searchValue: '',
            detail: null,
            isSearch: false,
            currentPage: 1,
            currentPage1: 1,
            choiceMark: null,
            oldChecked: ['楼栋', '单元'],
            pointMark: [],
            dyPointMark: [],
            dpPointMark: [],
            checkAll: true,
            checkedTypes: ['楼栋', '单元'],
            types: ['楼栋', '单元'],
            isIndeterminate: true,
            searchType: '0',
            menu: '',
            isDrag: false,
            data: [{
                label: '区域面',
                children: [{
                    label: '市',
                }, {
                    label: '区县',
                }, {
                    label: '乡镇',
                }, {
                    label: '网格',
                }]
            },
            {
                label: '道路',
                children: [{
                    label: '道路1',

                }, {
                    label: '道路2',

                }]
            },
            {
                label: '标注',
                children: [{
                    label: '建筑',

                }, {
                    label: '餐饮',

                }, {
                    label: '购物娱乐',

                }, {
                    label: '景区',

                }, {
                    label: '交通设施',

                }, {
                    label: '科教文化',

                }, {
                    label: '公共服务',

                }, {
                    label: '医疗保险',

                }, {
                    label: '休闲体育',

                }, {
                    label: '道路节点',

                }, {
                    label: '金融保险',

                }, {
                    label: '摩托车服务',

                }, {
                    label: '汽车服务',

                }]
            }
            ],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            activeName: '',
            date: moment().subtract(1, 'days').format('YYYY-MM-DD'),
            setDisabled: {
                disabledDate(time) {
                    return time.getTime() > Date.now();  // 可选历史天、可选当前天、不可选未来天
                },
            },
            area: '1002',
            checkList: [],
            optionsQx: [],
            optionsWg: [],
            options: [],
            value: '',
            value1: '',
            value2: '',
            search: '',
            mouseTool: null,
            drew: '',
            drewMarker: null,
            polygonMarker: null,
            polyEditor: null,
            drewOverlayGroup: null,
            pointOverlay: null,
            pointDyOverlay: null,
            pointDpOverlay: null,
            drewObj: null,
            isDrew: false,
            isTypeList: false,
            polygonMarks: [],
            typeList: [
                { name: '本网新上线', show: true },
                { name: '本网下线', show: true },
                { name: '本网存量', show: true },
                { name: '异网新上线', show: true },
                { name: '异网下线', show: true },
                { name: '异网存量', show: true },
                { name: '无宽带新上线', show: true },
                { name: '无宽带下线', show: true },
                { name: '无宽带存量', show: true }
            ],
            searchList: [],
            shopList: [],
            copyLeft: false,
            copyTop: 0,
            copyLeftPx: 0,
            copyRight: false,
            copyText: '',
            choicePolygon: null,
            showNum: true,
            showLeft: false,
            showRight: true,
            communityList: [],
            communityTotal: 0,
            fgqList: [],
            fgqFgShow: false,
            fgqFg: {},
            fgqTotal: 0,
            choiceDragPoint: null,
            choiceDragDyPoint: null,
            choiceDragDpPoint: null,
            dyList: [],
            mapCenter: [126.63297, 45.76175],
            changeDy: [],
            changeLd: [],
            changeDp: [],
            isSave: false,
            choicePolygonIndex: null,
            changePolygon: false,
            fgqType: 'community',
            haveIndicator: false
        }
    },
    async mounted() {
        this.loadAMap();
    },
    beforeDestroy() {
        this.map.off('zoomend', this.mapZoomend);
    },
    methods: {
        async loadAMap() {
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = this.isIE() ? `http://10.149.240.168:7003/ie/amap-jsapi.js` : `http://10.149.240.168:7003/jsapi.js`; // 判断是否ie11浏览器
            script.onload = async () => {
                await this.getMap();
                await this.getDateOldChange();
                await this.getUserInfo();
                await this.userLocation();
            };
            document.head.appendChild(script);
        },
        isIE() {
            const userAgent = navigator.userAgent;
            if (userAgent.indexOf("Trident") !== -1) {
                return true
            } else {
                return false
            }
        },
        // 是否显示指标
        getHaveIndicator() {
            this.haveIndicator = this.userInfo.account !== 'zaixian'
        },
        // 获取可选日期
        getDateOldChange() {
            getDate().then(res => {
                this.date = moment(res.res).format('YYYY-MM-DD');
                this.setDisabled = {
                    disabledDate(time) {
                        return time.getTime() > moment(res.res);  // 可选历史天、可选当前天、不可选未来天
                    },
                }
            });
        },
        // 修改地市联动
        changeOrgName() {
            let name = '黑龙江省'
            if (this.value2) {
                name = this.optionsWg.find(item => item.orgId === this.value2)?.name
            } else if (this.value1) {
                name = this.optionsQx.find(item => item.orgId === this.value1)?.name
            } else if (this.value) {
                name = this.options.find(item => item.orgId === this.value)?.name + '市'
            }
            this.$refs.numRef.changeName(name)
        },
        isHide() {
            this.dialogVisible = false;
            localStorage.setItem('isFirst', true);
        },
        // 去办理跳转
        goWinOpen(val, item) {
            this.goCopyText(val.fiberConverterStr);
            window.parent.parent.parent.postMessage(JSON.stringify({
                distCode: val.lastLev || item.lastLev || this.fgqFg.lastLev || '',
                propertyUnit: val.propertyunitCode || '',
                connectType: val.enterCode || '',
                long: this.choiceMark.longitude || '',
                weight: this.choiceMark.latitude || ''
            }), '*');
            setTimeout(() => {
                window.parent.parent.parent.closeWin();
            }, 1000);
        },
        // 展示分光器
        showFgqFg(item) {
            this.fgqFg = item;
            this.fgqFgShow = true;
        },
        // 隐藏分光器
        hideFgq() {
            if (this.fgqFgShow) {
                this.fgqFgShow = false;
            }
        },
        // 判断是否有拖拽权限
        getHaveDrag() {
            return this.userInfo.roleName && (this.userInfo.roleName.indexOf('市公司管理员') > -1 || this.userInfo.roleName.indexOf('省公司管理员') > -1) && !this.isIE()
        },
        // 小数截取
        getdistance(distance) {
            return distance ? Number(distance).toFixed(1) : 0;
        },
        // 获取小区名称
        getName(name) {
            let arr = name.split("|")
            return arr[arr.length - 1]
        },
        //获取全量列表
        postAllList() {
            this.loading = true;
            getAllList({
                pageNum: this.currentPage,
                pageSize: 9,
                userLng: this.mapCenter[0],
                userLat: this.mapCenter[1],
                cityCode: this.userInfo.cityCode || '',
                countyCode: this.userInfo.countyCode || '',
                gridId: this.userInfo.gridId || '',
                communityName: '',
                type: this.searchType == '0' || this.searchType == '2' ? '1' : '2'
            }).then(res => {
                this.communityList = res?.res?.list || [];
                this.communityTotal = res?.res?.total || 0;
                this.loading = false;
            });
        },
        // 获取市
        postCity() {
            getOrgList({ pid: '2300' }).then(res => {
                this.options = res.res || [];
                this.value = this.userInfo.cityCode || '';
            })
        },
        // 添加边界范围
        addArea() {
            getOrgList().then(res => {
                this.pointOverlay.removeOverlay(this.pointMark);
                this.pointDyOverlay.removeOverlay(this.dyPointMark);
                this.pointDpOverlay.removeOverlay(this.dpPointMark);
                this.drewOverlayGroup.removeOverlay(this.polygonMarker);
                let findItem = res.res[0]
                if (findItem && findItem.areaDistrict) {
                    polygonData = [this.getMultiPolygonToGeo(findItem.areaDistrict)] || [];
                    this.addPolygon(polygonData);
                    this.areaType = 'MultiPolygon'
                    let center = this.isIE() ? polygonCenter : this.getPolygonCenter();
                    this.map.setZoomAndCenter(7, center, false, 100);
                }
            });
        },
        // 市级别选择
        changeCity(val, flag) {
            if (val) {
                getOrgList({ pid: val }).then(res => {
                    this.optionsQx = res.res || [];
                    if (flag) {
                        this.value1 = this.userInfo.countyCode || '';
                    } else {
                        this.value1 = '';
                        this.value2 = '';
                    }
                    this.detail = null;
                    this.pointOverlay.removeOverlay(this.pointMark);
                    this.pointDyOverlay.removeOverlay(this.dyPointMark);
                    this.pointDpOverlay.removeOverlay(this.dpPointMark);
                    this.drewOverlayGroup.removeOverlay(this.polygonMarker);
                    let findItem = this.options.find(item => item.orgId === val);
                    if (findItem && findItem.areaDistrict) {
                        polygonData = [this.getMultiPolygonToGeo(findItem.areaDistrict)] || [];
                        this.addPolygon(polygonData);
                        this.map.setZoomAndCenter(9, [findItem.centerLng, findItem.centerLat], false, 100);
                    }
                    if (this.userInfo.countyCode && flag) {
                        this.changeDistrict(this.userInfo.countyCode, true);
                    } else {
                        this.startSearch();
                    }
                });
            } else {
                this.value1 = '';
                this.value2 = '';
                this.addArea();
                this.startSearch();
            }
        },
        // 区县选择
        changeDistrict(val, flag) {
            if (val) {
                getOrgList({ pid: val, upperOrgLevel: '3' }).then(res => {
                    this.optionsWg = res.res || [];
                    if (flag) {
                        this.value2 = this.userInfo.gridId || '';
                    } else {
                        this.value2 = '';
                    }
                    this.detail = null;
                    this.pointOverlay.removeOverlay(this.pointMark);
                    this.pointDyOverlay.removeOverlay(this.dyPointMark);
                    this.pointDpOverlay.removeOverlay(this.dpPointMark);
                    this.drewOverlayGroup.removeOverlay(this.polygonMarker);
                    let findItem = this.optionsQx.find(item => item.orgId === val);
                    if (findItem && findItem.areaDistrict) {
                        polygonData = [this.getMultiPolygonToGeo(findItem.areaDistrict)] || [];
                        this.addPolygon(polygonData);
                        this.map.setZoomAndCenter(12, [findItem.centerLng, findItem.centerLat], false, 100);
                    }
                    if (this.userInfo.gridId && flag) {
                        this.changeWg(this.userInfo.gridId);
                    } else {
                        this.startSearch();
                    }
                })
            } else {
                this.value2 = '';
                this.startSearch();
            }

        },
        // 网格选择
        changeWg(val) {
            let findItem = this.optionsWg.find(item => item.orgId === val);
            this.detail = null;
            this.pointOverlay.removeOverlay(this.pointMark);
            this.pointDyOverlay.removeOverlay(this.dyPointMark);
            this.pointDpOverlay.removeOverlay(this.dpPointMark);
            this.drewOverlayGroup.removeOverlay(this.polygonMarker);
            if (findItem && findItem.areaDistrict) {
                polygonData = [this.getMultiPolygonToGeo(findItem.areaDistrict)] || [];
                this.addPolygon(polygonData);
            }
            if (findItem && findItem.centerLng && findItem.centerLat) {
                this.map.setZoomAndCenter(14, [findItem.centerLng, findItem.centerLat], false, 100);
            }
            this.startSearch();
        },
        // 看板展开收起
        showPanel(pos) {
            this['show' + pos] = !this['show' + pos];
        },
        // 文字复制
        goCopyText(text) {
            let input = document.createElement('input');
            input.value = text || this.copyText;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            this.copyRight = false
            this.$message({
                message: '复制成功',
                type: 'success'
            })
        },
        // 获取用户登录信息
        getUserInfo() {
            try {
                getInfo().then(res => {
                    if (res.state_code == '1000') {
                        this.userInfo = res.res || {};
                        this.userLevel = res?.res?.userLevel || '';
                        this.getHaveIndicator();
                        this.postCity();
                        if (this.userInfo.cityCode) {
                            this.changeCity(this.userInfo.cityCode, true);
                        } else {
                            this.addArea()
                            this.getNumObject()
                        }
                    } else {
                        this.$message({
                            message: '获取登录用户信息失败',
                            type: 'warning'
                        })
                    }

                })
            } catch (error) {
                this.$message({
                    message: '获取登录用户信息失败！',
                    type: 'warning'
                })
            }
        },
        // 获取地图中心点
        userLocation() {
            try {
                getUserLocation().then(res => {
                    if (res.state_code == '1000') {
                        this.mapCenter = [res?.res?.centerLng, res?.res?.centerLat];
                        this.map.setZoomAndCenter(this.userInfo.countyCode ? 13 : 8, this.mapCenter, false, 100);
                        this.postAllList();
                        // // 创建定位插件实例
                        // const geolocation = new AMap.Geolocation({
                        //     enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                        //     timeout: 5000, // 超过10秒后停止定位，默认：5s
                        //     buttonPosition: 'RB', // 定位按钮的停靠位置
                        //     buttonOffset: new AMap.Pixel(10, 20), // 定位按钮距离对应角落的距离，默认：new AMap.Pixel(10, 20)
                        //     zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到相应级别，默认：true
                        // });
                        // geolocation.getCurrentPosition((status, result) => {
                        //     if (status == 'complete') {
                        //         // 定位成功，result即为定位结果信息
                        //         let position = result.position || {}
                        //         this.map.setZoomAndCenter(13, [position.lng, position.lat], false, 100);
                        //     } else {
                        //         // 定位失败，status为失败的原因描述。
                        //         console.error('定位失败', status, result); // 输出失败信息。
                        //     }
                        // });
                    }
                })
            } catch (error) {
                this.$message({
                    message: '获取登录用户地图中心点失败！',
                    type: 'warning'
                })
            }
        },
        // 地图图层挂载
        getMap() {
            this.initMap();
            this.pointOverlay = new AMap.OverlayGroup([])
            this.pointDyOverlay = new AMap.OverlayGroup([])
            this.pointDpOverlay = new AMap.OverlayGroup([])
            this.map.add(this.pointOverlay);
            this.map.add(this.pointDyOverlay);
            this.map.add(this.pointDpOverlay);
            this.drewOverlayGroup = new AMap.OverlayGroup([])
            this.map.add(this.drewOverlayGroup);

            // IE11兼容性处理：添加try-catch和延迟初始化
            try {
                // 检查AMap.PolygonEditor是否存在
                if (typeof AMap.PolygonEditor === 'undefined') {
                    this.polyEditor = null;
                    return;
                }

                // 使用setTimeout确保DOM完全加载
                setTimeout(() => {
                    try {
                        this.polyEditor = new AMap.PolygonEditor(this.map, null, {
                            editOptions: {
                                fillColor: "#fed151",
                                strokeColor: "#fed151",
                                strokeWeight: 4,
                            },
                            controlPoint: {
                                fillColor: "#fff",
                                strokeColor: "#fed151",
                                radius: 6
                            },
                            midControlPoint: {
                                fillColor: "#fff",
                                strokeColor: "#fed151",
                                radius: 6
                            }
                        });
                        let that = this;
                        this.polyEditor.on("end", function (event) {
                            let pointArr = event.target.getPath();
                            let arr = pointArr[0].map(function (item) {
                                return [item.lng, item.lat];
                            });
                            polygonData[that.choicePolygonIndex][0] = arr;
                        });
                    } catch (error) {
                        console.error('AMap.PolygonEditor initialization failed:', error);
                        this.polyEditor = null;
                    }
                }, this.isIE() ? 500 : 0); // IE11需要更长的延迟

            } catch (error) {
                console.error('PolygonEditor setup failed:', error);
                this.polyEditor = null;
            }
        },
        // 搜商铺（功能已迁移商铺地图）
        getSearchShopList() {
            this.checkedTypes = ['商铺']
            this.types = ['商铺']
            this.checkAll = true
            this.pointOverlay.removeOverlay(this.pointMark);
            this.pointDyOverlay.removeOverlay(this.dyPointMark);
            this.pointDpOverlay.removeOverlay(this.dpPointMark);
            this.showLeft = false;
            this.oldShopDetail = null;
            this.shopDetail = null;
            try {
                this.shopLoading = true;
                searchShopList({
                    pageNum: 1,
                    pageSize: 100,
                    cityCode: this.value || '',
                    countyCode: this.value1 || '',
                    gridId: this.value2 || '',
                    shopName: this.searchValue
                }).then(res => {
                    this.shopLoading = false;
                    this.shopList = res?.res?.list || [];
                    if (this.value2 || this.searchValue) {
                        pointDpData = [...this.shopList] || [];
                        this.pointDpOverlay.removeOverlay(this.dpPointMark);
                        this.addDpPoint();
                    }
                });
            } catch (error) {
                this.shopLoading = false;
                this.shopList = [];
            }
        },
        // 搜小区
        getSearchList(lng, lat) {
            try {
                this.loading = true;
                getAllList({
                    pageNum: 1,
                    pageSize: 50,
                    userLng: lng ? lng : this.mapCenter[0],
                    userLat: lat ? lat : this.mapCenter[1],
                    cityCode: this.value || '',
                    countyCode: this.value1 || '',
                    gridId: this.value2 || '',
                    communityName: lng ? '' : this.searchValue,
                    type: this.searchType == '0' || this.searchType == '2' ? '1' : '2'
                }).then(res => {
                    this.loading = false;
                    this.searchList = res?.res?.list || [];
                });
                this.getNumObject()
            } catch (error) {
                this.loading = false;
                this.searchList = [];
            }
        },
        // 左侧指标数量
        getNumObject() {
            let statDate = moment(this.date).format('YYYYMMDD')
            getNumList({ statDate, orgLevel: this.value2 ? '4' : this.value1 ? '3' : this.value ? '2' : '1', orgId: this.value2 || this.value1 || this.value || '2300' }).then(res => {
                let dataList = res?.res || []
                this.numObj = {
                    khfe: dataList.find(item => item.userCode == '45')?.userValue2 || '',
                    khfezf: dataList.find(item => item.userCode == '45')?.userValue3 || '',
                    kdfezf: dataList.find(item => item.userCode == '47')?.userValue3 || '',
                    ltfezf: dataList.find(item => item.userCode == '42')?.userValue3 || '',
                    dxfezf: dataList.find(item => item.userCode == '43')?.userValue3 || '',
                    kdfe: dataList.find(item => item.userCode == '47')?.userValue2 || '',
                    ltfe: dataList.find(item => item.userCode == '42')?.userValue2 || '',
                    dxfe: dataList.find(item => item.userCode == '43')?.userValue2 || '',
                    fzzxqs: dataList.find(item => item.userCode == '48')?.userValue2 || '',
                    dfe: dataList.find(item => item.userCode == '49')?.userValue2 || '',
                    xqgm: dataList.find(item => item.userCode == '50')?.userValue2 || '',
                }
            })
            this.changeOrgName()
        },
        // 延时查询
        setTimeOutSearch() {
            if (this.searchType === '0') {
                this.loading = true;
                this.getSearchList();
            }
            if (this.searchType === '1') {
                this.shopLoading = true;
                this.getSearchShopList();
            }
            if (this.searchType === '2') {
                this.loading = true;
                try {
                    let city = '';
                    if (this.value) {
                        let find = this.options.find(item => item.orgId === this.value)
                        if (find) {
                            city = find.name || ''
                        }
                    }
                    if (this.search) {
                        getPlaceLocation({ address: this.search, city: city || this.userInfo.cityName || this.userInfo.provinceName }).then(res => {
                            let reson = res.res || {}
                            if (reson.code == 0) {
                                let list = reson?.data?.list || []
                                this.loading = false;
                                if (list.length) {
                                    let location = list[0].location;
                                    let loc = location.split(',');
                                    this.getSearchList(loc[0], loc[1]);
                                } else {
                                    this.$message({
                                        message: '未查询到对应位置',
                                        type: 'warning'
                                    })
                                    this.loading = false;
                                    this.searchList = [];
                                }
                            } else {
                                this.$message({
                                    message: '未查询到对应位置',
                                    type: 'warning'
                                })
                                this.loading = false;
                                this.searchList = [];
                            }
                        }).catch(error => {
                            this.loading = false;
                            this.searchList = [];
                        })
                    }

                } catch (error) {
                    this.loading = false;
                    this.searchList = [];
                }

            }
        },
        // 点位筛选
        changeType(val) {
            if (val == '1') {
                this.checkedTypes = ['商铺']
                this.types = ['商铺']
                this.checkAll = true
                this.shopListShow = true;
                this.listShow = false;
            } else {
                this.checkedTypes = ['楼栋', '单元']
                this.types = ['楼栋', '单元']
                this.checkAll = true
                this.shopListShow = false;
                this.listShow = true;
            }
            this.detail = null;
            this.shopDetail = null;
            this.pointOverlay.removeOverlay(this.pointMark);
            this.pointDpOverlay.removeOverlay(this.dpPointMark);
            this.drewOverlayGroup.removeOverlay(this.polygonMarker);
            this.pointDyOverlay.removeOverlay(this.dyPointMark);
            if (this.value2) {
                this.changeWg(this.value2);
            } else if (this.value1) {
                this.changeDistrict(this.value1);
            } else if (this.value) {
                this.changeCity(this.value);
            } else {
                this.startSearch();
            }
        },
        // 搜索小区
        startSearch() {
            this.searchValue = this.search;
            this.searchList = [];
            this.shopList = [];
            if (!this.loading || !this.shopLoading) {
                this.setTimeOutSearch();
            } else {
                setTimeout(() => {
                    this.searchList = [];
                    this.shopList = [];
                    this.setTimeOutSearch();
                }, 2000)
            }
        },
        // 使用 Wkt.parse 方法解析 WKT
        getMultiPolygonToGeo(wktString) {
            const geojson = WKT.parse(wktString);
            return geojson.coordinates
        },
        getPolygonCenter() {
            let geojson = {
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "properties": {},
                        "geometry": {
                            "type": 'MultiPolygon',
                            "coordinates": polygonData
                        }
                    }
                ]
            }
            const center = turf.center(geojson); // 计算中心点
            return center.geometry.coordinates;
        },
        // 保存
        getSave(flag) {
            this.closeDrag();
            if (flag) {
                try {
                    if (this.changePolygon) {
                        let center = this.isIE() ? polygonCenter : this.getPolygonCenter();
                        let geojson = {
                            "type": "MultiPolygon",
                            "coordinates": polygonData
                        };
                        let wktString = WKT.convert(geojson);
                        let params = {
                            communityCode: this.detail.communityCode,
                            centerLng: center[0],
                            centerLat: center[1],
                            areaDistrict: wktString,
                            maxLng: this.detail.maxLng,
                            maxLat: this.detail.maxLat,
                            minLng: this.detail.minLng,
                            minLat: this.detail.minLat
                        }
                        editCommunity({ ...params }).then(res => { });
                    }

                    if (this.changeLd.length) {
                        let buildings = this.changeLd.map(item => {
                            return {
                                editCode: item?.pointId || '',
                                longitude: item?.lnglat?.lng || '',
                                latitude: item?.lnglat?.lat || '',
                            }
                        })
                        editBuildings({ buildings }).then(res => { });
                    }

                    if (this.changeDy.length) {
                        let units = this.changeDy.map(item => {
                            return {
                                editCode: item?.pointId || '',
                                longitude: item?.lnglat?.lng || '',
                                latitude: item?.lnglat?.lat || '',
                            }
                        })
                        editUnits({ units }).then(res => { });
                    }
                    if (this.changeDp.length) {
                        let shop = this.changeDp.map(item => {
                            return {
                                shopId: item?.pointId || '',
                                longitude: item?.lnglat?.lng || '',
                                latitude: item?.lnglat?.lat || '',
                            }
                        })
                        editShops({ ...shop[0] }).then(res => { });
                    }
                    if (this.searchType !== '1') {
                        this.startSearch();
                    }
                    this.getClose();
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    });
                    this.isSave = false;
                } catch (error) {
                    this.$message({
                        message: '操作失败',
                        type: 'success'
                    });
                    console.log('error', error)
                }

            }
        },
        // 关闭拖拽
        closeDrag() {
            // this.map.remove(this.newMark);
            // this.newMark = null;
            if (this.choiceDragPoint) {
                this.choiceDragPoint.setIcon(new AMap.Icon({
                    size: new AMap.Size(26, 31),
                    image: build,
                    imageSize: new AMap.Size(26, 31)
                }));
                this.choiceDragPoint.setDraggable(false);
                this.choiceDragPoint = null;
            }
            if (this.choiceDragDyPoint) {
                this.choiceDragDyPoint.setIcon(point);
                this.choiceDragDyPoint.setDraggable(false);
                this.choiceDragDyPoint = null;
            }
            if (this.choiceDragDpPoint) {
                this.choiceDragDpPoint.setIcon(point);
                this.choiceDragDpPoint.setDraggable(false);
                this.choiceDragDpPoint = null;
            }
            if (this.choicePolygon) {
                this.polyEditor.setTarget();
                this.polyEditor.close();
                this.choicePolygon = null;
            }
        },
        // 取消操作
        getClose(flag) {
            if (flag) {
                if (this.changePolygon) {
                    this.drewOverlayGroup.removeOverlay(this.polygonMarker);
                    polygonData = this.areaType == 'MultiPolygon' ? this.getMultiPolygonToGeo(this.oldDetail.areaDistrict) : this.areaType == 'Polygon' ? [this.getMultiPolygonToGeo(this.oldDetail.areaDistrict)] : [];
                    this.addPolygon(polygonData);
                };
                if (this.changeLd.length) {
                    this.pointOverlay.removeOverlay(this.pointMark);
                    pointLdData = this.oldDetail.buildList || [];
                    this.addPoint();
                };
                if (this.changeDy.length) {
                    this.pointDyOverlay.removeOverlay(this.dyPointMark);
                    pointDyData = this.oldDetail.unitList || [];
                    this.addDyPoint();
                };
                if (this.changeDp.length) {
                    this.pointDpOverlay.removeOverlay(this.dpPointMark);
                    pointDpData = [{ ...this.oldShopDetail }];
                    this.addDpPoint();
                };
            }
            this.changePolygon = false;
            this.closeDrag();
            this.isDrag = false;
            this.changeLd = [];
            this.changeDy = [];
            this.changeDp = [];
            this.choicePolygonIndex = null;
            this.isSave = false;
            // this.pointOverlay._overlays[0].map(marker => {
            //     marker.setDraggable(false);
            // })
            // this.pointDyOverlay._overlays[0].map(marker => {
            //     marker.setDraggable(false);
            // })
            // this.choicePolygon.off('click', this.openEditor)
        },
        // 打开编辑
        openEditor() {
            this.polyEditor.open();
        },
        // 分页
        handleCurrentChange(val) {
            this.currentPage = val;
            this.postAllList();
        },
        // 分页
        handleCurrentChange1(val) {
            this.currentPage1 = val;
            this.postFgq()
        },
        // 隐藏搜索
        hideSearch() {
            this.isSearch = false;
            this.detail = null;
        },
        // 搜索
        goSearch() {
            if (this.choiceMark) {
                this.choiceMark = null;
                this.fgqList = [];
            }
            if (!this.isSearch) {
                this.startSearch();
                this.isSearch = true;
            }
            this.showDyList = false;
        },
        // 全选
        handleCheckAllChange(val) {
            this.checkedTypes = val ? this.searchType === '1' ? ['楼栋', '单元', '商铺'] : ['楼栋', '单元'] : [];
            this.oldChecked = val ? this.searchType === '1' ? ['楼栋', '单元', '商铺'] : ['楼栋', '单元'] : [];
            this.isIndeterminate = false;
            if (val) {
                this.addPoint();
                this.addDyPoint();
                this.addDpPoint();
            } else {
                this.pointOverlay.removeOverlay(this.pointMark);
                this.pointDyOverlay.removeOverlay(this.dyPointMark);
                this.pointDpOverlay.removeOverlay(this.dpPointMark);
            }
        },
        // 筛选点位
        handleCheckedTypesChange(value) {
            let diff = this.findDifferences(value, this.oldChecked)[0];
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.types.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.types.length;
            let isLd = value.includes('楼栋');
            let isDy = value.includes('单元');
            let isSp = value.includes('商铺');
            if (isLd) {
                if (diff === '楼栋') {
                    this.addPoint();
                }
            } else {
                this.pointOverlay.removeOverlay(this.pointMark);
            }
            if (isDy) {
                if (diff === '单元') {
                    this.addDyPoint();
                }
            } else {
                this.pointDyOverlay.removeOverlay(this.dyPointMark);
            }
            if (isSp) {
                if (diff === '商铺') {
                    this.addDpPoint();
                }
            } else {
                this.pointDpOverlay.removeOverlay(this.dpPointMark);
            }
            this.oldChecked = value;
        },
        // 获取数组不同
        findDifferences(arr1, arr2) {
            const set1 = new Set(arr1);
            const set2 = new Set(arr2);
            const diff1 = Array.from(set1).filter(x => !set2.has(x));
            const diff2 = Array.from(set2).filter(x => !set1.has(x));
            return [...diff1, ...diff2];
        },
        // 返回
        goBackMenu() {
            this.menu = ''
        },
        // 拖拽点击
        setDrag() {
            // 在IE浏览器中禁用编辑功能
            if (this.isIE()) {
                this.$message({
                    message: 'IE浏览器暂不支持编辑功能',
                    type: 'warning'
                });
                return;
            }

            this.isDrag = !this.isDrag;
            if (!this.isDrag) {
                this.getClose(true);
            }
        },
        // 创建地图
        initMap() {
            let xyzTileLayer = new AMap.TileLayer({
                mapNumber: 'GS(2019)6379',
                getTileUrl: function (x, y, z) {
                    var str = ['', '01', '02', '03', '04'];
                    var a = 'http://10.149.240.168:7003/api/appmaptile?x=' + x + '&y=' + y + '&z=' + z;
                    return a.replace('{}', str[(x + y) % 5]);
                },
                zIndex: 1
            });
            this.map = new AMap.Map('map', {
                viewMode: '3D',
                layers: [xyzTileLayer],
                zoom: 13,
                zooms: [3, 18],
                // offlineServer: "http://10.149.240.167:7002/api",
                center: this.mapCenter
            });
            this.map.on('zoomend', this.mapZoomend);
        },
        mapZoomend() {
            let zoom = this.map.getZoom();
            let zoomSize = { '18': 1, '17': 1, '16': 0.9, '15': 0.7, '14': 0.6, '13': 0.5, '12': 0.4, '11': 0.3, '10': 0.2, '9': 0.1, '8': 0.1, '7': 0.1, '6': 0.1, '5': 0.1, '4': 0.1, '3': 0.1 }
            let size = zoomSize[zoom] || 1;
            let iconSize = 14 * size;
            if (this.dyPointMark && this.dyPointMark.length) {
                this.dyPointMark.map((mark,idx) => {
                    mark.setIcon(new AMap.Icon({
                        size: new AMap.Size(iconSize, iconSize),
                        image: point,
                        imageSize: new AMap.Size(iconSize, iconSize)
                    }))
                    if (zoom < 16) {
                        mark.setLabel({ content: '' });
                    } else {
                        mark.setLabel({
                            direction: 'center',
                            content: this.updateText(pointDyData[idx].unitName)
                        });
                    }
                })
            }
        },
        //添加店铺
        addDpPoint() {
            let points = pointDpData;
            this.dpPointMark = points.map(marker => {
                let mark = this.createMarker({
                    longitude: marker.longitude,
                    latitude: marker.latitude,
                    icon: shop,
                    iconSize: [26, 31, 15]
                });
                mark.on('click', (e) => {
                    this.choiceMark = null
                    this.fgqType = 'shop'
                    this.showRight = true;
                    this.fgqList = [];
                    this.showDyList = true;
                    if ((!this.choiceDragPoint) && (!this.choiceDragDyPoint) && (!this.choiceDragDpPoint) && !this.choicePolygon && this.isDrag) {
                        this.choiceDragDpPoint = mark;
                        this.choiceDragDpPoint.setIcon(new AMap.Icon({
                            size: new AMap.Size(26, 31),
                            image: shop,
                            imageSize: new AMap.Size(26, 31),
                        }));
                        this.choiceDragDpPoint.setDraggable(true);
                    } else {
                        if (this.isDrag) {
                            this.$message({
                                message: '请确定当前操作后，再继续其他拖拽操作！',
                                type: 'warning'
                            })
                        }
                    }
                    this.getShopsDetail(marker.shopId, marker.gridId);
                });
                let that = this;
                mark.on('dragend', function (e) {
                    let position = mark.getPosition(); // 获取当前位置
                    let anchorPixel = that.map.lngLatToContainer([position.lng, position.lat]); // 将经纬度转换为地图容器中的像素坐标
                    let bottomCenterPixel = [anchorPixel.x, anchorPixel.y]; // 计算底部中心点像素坐标（通常向下偏移半个高度）
                    let bottomCenterLngLat = that.map.containerToLngLat(bottomCenterPixel); // 将像素坐标转换回经纬度坐标
                    // 拖动结束时执行的函数
                    let idx = that.changeDp.findIndex(item => item.pointId == marker.shopId);
                    if (idx > -1) {
                        that.changeDp[idx] = { lnglat: bottomCenterLngLat, pointId: marker.shopId };
                    } else {
                        that.changeDp.push({ lnglat: bottomCenterLngLat, pointId: marker.shopId });
                    }
                    that.isSave = true;
                });
                return mark
            });
            this.pointDpOverlay.addOverlay(this.dpPointMark);
        },
        // 获取分光器列表
        postFgq() {
            this.loading = true;
            getFgq({
                pageNum: this.currentPage1,
                pageSize: 4,
                communityCode: this.searchType == '1' ? this.choiceMark.communityCode : this.detail.communityCode,
                buildingCode: this.choiceMark.buildingCode,
                unitCode: this.choiceMark.unitCode,
            }).then(res => {
                this.fgqList = res?.res?.list || [];
                this.fgqTotal = res?.res?.total || 0;
                this.loading = false;
            })
        },
        updateText(str) {
            let updatedStr = str.replace(/单元/g, "");
            return updatedStr;
        },
        // 添加单元点位
        addDyPoint() {
            let points = pointDyData;
            this.dyPointMark = points.map(marker => {
                let mark = new AMap.Marker({
                    position: new AMap.LngLat(marker.longitude, marker.latitude),
                    icon: new AMap.Icon({
                        size: new AMap.Size(14, 14),
                        image: point,
                        imageSize: new AMap.Size(14, 14)
                    }),
                    anchor: 'center',
                    offset: new AMap.Pixel(0, 0),
                    label: {
                        direction: 'center',
                        content: this.updateText(marker.unitName),
                    },
                    draggable: false
                });
                mark.on('click', (e) => {
                    this.choiceMark = marker
                    this.fgqType = 'unit'
                    this.fgqList = [];
                    this.currentPage1 = 1;
                    this.postFgq();
                    this.showDyList = false;
                    if ((!this.choiceDragPoint) && (!this.choiceDragDyPoint) && !this.choicePolygon && this.isDrag) {
                        this.choiceDragDyPoint = mark;
                        this.choiceDragDyPoint.setIcon(point1);
                        this.choiceDragDyPoint.setDraggable(true);
                    } else {
                        if (this.isDrag) {
                            this.$message({
                                message: '请确定当前操作后，再继续其他拖拽操作！',
                                type: 'warning'
                            })
                        }
                    }
                });
                let that = this;
                mark.on('dragend', function (e) {
                    // 拖动结束时执行的函数
                    let idx = that.changeDy.findIndex(item => item.pointId == marker.unitCode)
                    if (idx > -1) {
                        that.changeDy[idx] = { lnglat: e.lnglat, pointId: marker.unitCode };
                    } else {
                        that.changeDy.push({ lnglat: e.lnglat, pointId: marker.unitCode });
                    }
                    that.isSave = true;
                });
                return mark
            });
            this.pointDyOverlay.addOverlay(this.dyPointMark);
        },
        // showNewMark(marker) {
        //     this.newMark = new AMap.ElasticMarker({ 
        //         position: new AMap.LngLat(marker.longitude, marker.latitude),
        //         styles: [{
        //             icon: {
        //                 size: new AMap.Size(26, 31),
        //                 img: addressActive,
        //                 imageSize: new AMap.Size(26, 31),
        //                 fitZoom: 17.5,
        //                 scaleFactor: 2,
        //                 maxScale: 1,
        //                 minScale: 0.1,
        //                 anchor: 'bottom-center',
        //             },
        //         }],
        //         zoomStyleMapping: {
        //             14: 0,
        //             15: 0,
        //             16: 0,
        //             17: 0,
        //             18: 0,
        //             19: 0,
        //             20: 0
        //         },
        //         draggable: true
        //     });
        //     this.map.add(this.newMark);
        //     let that = this;
        //     this.newMark.on('dragend', function (e) {
        //         let position = this.newMark._position; // 获取当前位置
        //         let anchorPixel = that.map.lngLatToContainer([position.lng, position.lat]); // 将经纬度转换为地图容器中的像素坐标
        //         let bottomCenterPixel = [anchorPixel.x, anchorPixel.y]; // 计算底部中心点像素坐标（通常向下偏移半个高度）
        //         let bottomCenterLngLat = that.map.containerToLngLat(bottomCenterPixel); // 将像素坐标转换回经纬度坐标
        //         // 拖动结束时执行的函数
        //         let idx = that.changeLd.findIndex(item => item.pointId == marker.buildingCode);
        //         if (idx > -1) {
        //             that.changeLd[idx] = { lnglat: bottomCenterLngLat, pointId: marker.buildingCode };
        //         } else {
        //             that.changeLd.push({ lnglat: bottomCenterLngLat, pointId: marker.buildingCode });
        //         }
        //         that.isSave = true;
        //     });
        // },
        // 创建Marker的通用方法
        createMarker(options) {
            const { longitude, latitude, icon, iconSize, label, zoomStyleMapping } = options;

            if (this.isIE()) {
                return new AMap.Marker({
                    position: new AMap.LngLat(longitude, latitude),
                    styles: [{
                        icon: {
                            size: new AMap.Size(iconSize[0], iconSize[1]),
                            image: icon,
                            imageSize: new AMap.Size(iconSize[0], iconSize[1]),
                            fitZoom: iconSize[2] || 15,
                            scaleFactor: 2,
                            maxScale: 1,
                            minScale: 0.2,
                            anchor: 'bottom-center',
                        },
                        ...(label && { label })
                    }],
                });
            } else {
                return new AMap.ElasticMarker({
                    position: new AMap.LngLat(longitude, latitude),
                    styles: [{
                        icon: {
                            size: new AMap.Size(iconSize[0], iconSize[1]),
                            image: icon,
                            imageSize: new AMap.Size(iconSize[0], iconSize[1]),
                            fitZoom: iconSize[2] || 15,
                            scaleFactor: 2,
                            maxScale: 1,
                            minScale: 0.2,
                            anchor: 'bottom-center',
                        },
                        ...(label && { label })
                    }],
                    zoomStyleMapping: zoomStyleMapping || {
                        12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0
                    },
                });
            }
        },
        // 添加基础点
        addPoint() {
            let points = pointLdData;
            this.pointMark = points.map(marker => {
                let mark = '';
                if (this.isIE()) {
                    mark = new AMap.Marker({
                        position: new AMap.LngLat(marker.longitude, marker.latitude),
                        icon: new AMap.Icon({
                            size: new AMap.Size(26, 31),
                            image: build,
                            imageSize: new AMap.Size(26, 31)
                        }),
                        anchor: 'top-center',
                        draggable: false,
                    });
                } else {
                    mark = new AMap.ElasticMarker({
                        position: new AMap.LngLat(marker.longitude, marker.latitude),
                        styles: [{
                            icon: {
                                size: new AMap.Size(26, 31),
                                img: build,
                                imageSize: new AMap.Size(26, 31),
                                fitZoom: 17.5,
                                scaleFactor: 2,
                                maxScale: 1,
                                minScale: 0.1,
                                anchor: 'bottom-center',
                            },
                        }],
                        zoomStyleMapping: {
                            14: 0,
                            15: 0,
                            16: 0,
                            17: 0,
                            18: 0,
                            19: 0,
                            20: 0
                        },
                    });
                }
                mark.on('click', (e) => {
                    this.choiceMark = marker
                    this.fgqType = 'building'
                    this.fgqList = [];
                    this.currentPage1 = 1;
                    this.showRight = true;
                    this.postFgq();
                    this.showDyList = false;
                    if ((!this.choiceDragPoint) && (!this.choiceDragDyPoint) && !this.choicePolygon && this.isDrag) {
                        this.choiceDragPoint = mark;
                        this.choiceDragPoint.setIcon(new AMap.Icon({
                            size: new AMap.Size(26, 31),
                            image: addressActive,
                            imageSize: new AMap.Size(26, 31),
                        }));
                        // this.choiceDragPoint.hide();
                        // this.showNewMark(marker);
                        this.choiceDragPoint.setDraggable(true);
                    } else {
                        if (this.isDrag) {
                            this.$message({
                                message: '请确定当前操作后，再继续其他拖拽操作！',
                                type: 'warning'
                            })
                        }
                    }
                });
                let that = this;
                mark.on('dragend', function (e) {
                    let position = mark.getPosition(); // 获取当前位置
                    let anchorPixel = that.map.lngLatToContainer([position.lng, position.lat]); // 将经纬度转换为地图容器中的像素坐标
                    let bottomCenterPixel = [anchorPixel.x, anchorPixel.y]; // 计算底部中心点像素坐标（通常向下偏移半个高度）
                    let bottomCenterLngLat = that.map.containerToLngLat(bottomCenterPixel); // 将像素坐标转换回经纬度坐标
                    // 拖动结束时执行的函数
                    let idx = that.changeLd.findIndex(item => item.pointId == marker.buildingCode);
                    if (idx > -1) {
                        that.changeLd[idx] = { lnglat: bottomCenterLngLat, pointId: marker.buildingCode };
                    } else {
                        that.changeLd.push({ lnglat: bottomCenterLngLat, pointId: marker.buildingCode });
                    }
                    that.isSave = true;
                });
                return mark
            });
            // if(this.choiceDragPoint){
            //     this.choiceDragPoint.show();
            // }
            this.pointOverlay.addOverlay(this.pointMark);
        },
        // 添加多边形
        addPolygon(data) {
            this.polygonMarker = data.map((path, i) => {
                let mark = new AMap.Polygon({
                    path,
                    strokeColor: "#fed151",
                    strokeOpacity: 1,
                    strokeWeight: 2,
                    fillColor: '#fed151',
                    fillOpacity: 0.1,
                    strokeStyle: 'solid',
                });
                mark.on('click', (e) => {
                    if (!this.choiceDragPoint && !this.choiceDragDyPoint && !this.choicePolygon && this.isDrag) {
                        this.changePolygon = true;
                        this.polyEditor.close();
                        this.polyEditor.setTarget(mark);
                        this.polyEditor.open();
                        this.choicePolygon = mark
                        this.isSave = true;
                        this.choicePolygonIndex = i;
                    } else {
                        if (this.isDrag) {
                            this.$message({
                                message: '请确定当前操作后，再继续其他拖拽操作！',
                                type: 'warning'
                            })
                        }
                    }
                    // this.choicePolygon.on('click', this.openEditor)
                });
                return mark;
            })
            this.drewOverlayGroup.addOverlay(this.polygonMarker);
        },
        // 添加方形
        // addRectangle(path) {
        //     console.log('path', path)
        //     let southWest = new AMap.LngLat(path[0][0], path[0][1])
        //     let northEast = new AMap.LngLat(path[2][0], path[2][1])
        //     let bounds = new AMap.Bounds(southWest, northEast)
        //     this.drewMarker = new AMap.Rectangle({
        //         bounds: bounds,
        //         strokeColor: "#62adf5",
        //         strokeOpacity: 1,
        //         strokeWeight: 4,
        //         fillColor: '#62adf5',
        //         fillOpacity: 0.2,
        //         strokeStyle: 'solid',
        //     });
        //     this.drewOverlayGroup.addOverlay(this.drewMarker);
        //     this.polyEditor = new AMap.RectangleEditor(this.map);
        //     this.polyEditor.close();
        //     this.polyEditor.setTarget(this.drewMarker);
        //     this.polyEditor.open();
        // },
        // 确定拖拽结果
        isOk() {
            this.polyEditor && this.polyEditor.close();
            this.drew = '';
            this.drewObj = null;
            this.isTypeList = true;
            // this.isDrew = false;
        },
        // 取消
        clear() {
            this.polyEditor && this.polyEditor.close();
            this.drew = '';
            this.drewObj && this.map.remove(this.drewObj);
            this.isDrew = false;
            this.mouseTool && this.mouseTool.close(true);
        },
        // 绘制
        drewTool(drew) {
            this.drew = drew
            if (this.mouseTool) {
                this.mouseTool.close(true); // 清除所有绘制内容
            }
            if (this.polyEditor) {
                this.polyEditor.close();
            }
            if (drew === '0') {
                this.drawCircle()
            } else if (drew === '1') {
                this.drawRectangle()
            } else if (drew === '2') {
                this.drawPolygon()
            }
        },
        // 画线
        drawPolyline() {
            this.mouseTool.polyline({
                strokeColor: "#3366FF",
                strokeOpacity: 1,
                strokeWeight: 6,
                // 线样式还支持 'dashed'
                strokeStyle: "solid",
                // strokeStyle是dashed时有效
                // strokeDasharray: [10, 5],
            })
        },
        // 画多边形
        drawPolygon() {
            this.mouseTool.polygon({
                strokeColor: "#62adf5",
                strokeOpacity: 1,
                strokeWeight: 4,
                fillColor: '#62adf5',
                fillOpacity: 0.2,
                strokeStyle: 'solid',
            })
        },
        // 画方形
        drawRectangle() {
            this.mouseTool.rectangle({
                strokeColor: "#62adf5",
                strokeOpacity: 1,
                strokeWeight: 4,
                fillColor: '#62adf5',
                fillOpacity: 0.2,
                strokeStyle: 'solid',
            })
        },
        // 画圆
        drawCircle() {
            this.mouseTool.circle({
                strokeColor: "#62adf5",
                strokeOpacity: 1,
                strokeWeight: 4,
                fillColor: '#62adf5',
                fillOpacity: 0.2,
                strokeStyle: 'solid'
            })
        },
        // 关闭绘制
        closeEdit() {
            editor && editor.close();
            editor = null;
        },
        // 展示点位
        showPoint(i) {
            if (this.typeList[i].show) {
                cluster.setData([]);
                this.typeList[i].show = false;
            } else {
                cluster.setData(points);
                this.typeList[i].show = true;
            }
        },
        // 调整中心点
        setMapCenter(item) {
            if (this.searchType === '0' || this.searchType === '2') {
                this.communityDetail(item.communityCode);
            }
            if (this.searchType === '1') {
                this.getShopsDetail(item.shopId, item.gridId);
            }
            this.getClose();
            this.showLeft = true;
        },
        // 单元
        setDyCenter(item) {
            this.map.setZoomAndCenter(17, [item.lng, item.lat], false, 100);
            this.choiceMark = item;
            this.currentPage1 = 1;
            this.fgqList = [];
            this.postFgq();
            this.showDyList = false;
        },
        // 隐藏列表
        hideList() {
            this.choiceMark = null;
            this.fgqList = [];
            this.showDyList = true;
        },
        // 修改日期
        getDateDetail() {
            if (this.detail) {
                this.communityDetail(this.detail.communityCode);
            } else {
                this.getNumObject()
            }
        },
        // 获取商铺详情
        async getShopsDetail(shopId, gridId) {
            this.showLeft = true;
            try {
                this.checkedTypes = ['楼栋', '单元', '商铺']
                this.types = ['楼栋', '单元', '商铺']
                this.checkAll = true
                this.pointOverlay.removeOverlay(this.pointMark);
                this.pointDpOverlay.removeOverlay(this.dpPointMark);
                // this.drewOverlayGroup.removeOverlay(this.polygonMarker);
                this.pointDyOverlay.removeOverlay(this.dyPointMark);
                let list = []
                // 获取店铺详情
                await getShopDetail({ shopId }).then(res => {
                    this.oldShopDetail = res.res || {}
                    this.shopDetail = res.res || {}
                    this.map.setZoomAndCenter(17, [res.res.longitude, res.res.latitude], false, 100);
                    pointDpData = [{ ...res.res }] || [];
                    this.addDpPoint();
                })
                // 根据商铺搜索楼栋接口（100米内）
                await shopsNearBuildingList({ shopId, gridId }).then(res => {
                    res.res.map(item => {
                        list.push({ ...item, title: item.buildingName, lng: item.longitude, lat: item.latitude })
                    });
                    pointLdData = res.res || [];
                    this.oldDetail.buildList = [...pointLdData]
                    this.addPoint(true);
                })
                // 根据商铺搜索单元接口（100米内）
                await getShopUints({ shopId, gridId }).then(res => {
                    this.dyList.push
                    res.res.map(item => {
                        list.push({ ...item, title: item.buildingName + '-' + item.unitName, lng: item.longitude, lat: item.latitude })
                    });
                    pointDyData = res.res || [];
                    this.oldDetail.unitList = [...pointDyData]
                    this.addDyPoint(true);
                })
                await this.getList(list);
            } catch (error) {
                console.log('error', error)
            }
        },
        // 获取单元列表
        getList(list) {
            this.showDyList = true;
            this.dyList = list;
        },
        // 获取小区详情
        communityDetail(communityCode) {
            try {
                this.types = ['楼栋', '单元']
                this.checkedTypes = ['楼栋', '单元']
                this.checkAll = true
                let statDate = moment(this.date).format('YYYYMMDD')
                getCommunityDetail({ communityCode, statDate }).then(res => {
                    this.oldDetail = res.res || {}
                    this.detail = res.res || {}
                    this.pointOverlay.removeOverlay(this.pointMark);
                    this.pointDyOverlay.removeOverlay(this.dyPointMark);
                    this.pointDpOverlay.removeOverlay(this.dpPointMark);
                    this.drewOverlayGroup.removeOverlay(this.polygonMarker);
                    polygonCenter = [res.res.centerLng, res.res.centerLat];
                    if (this.detail.areaDistrict) {
                        this.areaType = this.detail.areaDistrict.indexOf('MULTIPOLYGON') > -1 ? 'MultiPolygon' : 'Polygon'
                        polygonData = this.areaType == 'MultiPolygon' ? this.getMultiPolygonToGeo(this.detail.areaDistrict) : this.areaType == 'Polygon' ? [this.getMultiPolygonToGeo(this.detail.areaDistrict)] : [];
                        this.addPolygon(polygonData);
                        // 获取中心点
                        let center = this.isIE() ? polygonCenter : this.getPolygonCenter();
                        this.map.setZoomAndCenter(17, center, false, 100);
                    }
                    pointLdData = this.detail.buildList || [];
                    this.addPoint();
                    // this.addDpPoint();
                    pointDyData = this.detail.unitList || [];
                    this.addDyPoint(true);
                    let dyList = []
                    pointLdData.map(item => {
                        dyList.push({ ...item, title: item.buildingName, lng: item.longitude, lat: item.latitude })
                    })
                    pointDyData.map(item => {
                        dyList.push({ ...item, title: item.buildingName + '-' + item.unitName, lng: item.longitude, lat: item.latitude })
                    })
                    this.dyList = dyList;
                    this.showDyList = true;
                })
            } catch (error) {
                console.log('error', error)
            }

        },
        // 添加聚合图层
        addCluster() {
            cluster = new AMap.MarkerCluster(this.map, points, {
                gridSize: gridSize, // 设置网格像素大小
                renderClusterMarker: this._renderClusterMarker, // 自定义聚合点样式
                renderMarker: this._renderMarker, // 自定义非聚合点样式
            });
        },
        // 自定义聚合点样式
        _renderClusterMarker(context) {
            let div = document.createElement('div');
            let bgColor = '#3d9dfe';
            let fontColor = '#fff';
            div.style.backgroundColor = bgColor;
            let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
            div.style.width = div.style.height = size + 'px';
            div.style.borderRadius = size / 2 + 'px';
            div.innerHTML = context.count;
            div.style.lineHeight = size + 'px';
            div.style.color = fontColor;
            div.style.fontSize = '18px';
            div.style.textAlign = 'center';
            context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
            context.marker.setContent(div);
        },
        // 自定义非聚合点样式
        _renderMarker(context) {
            let content = `<img src="${address}"/>`;
            let offset = new AMap.Pixel(-20, -35);
            context.marker.setContent(content)
            context.marker.setOffset(offset)
        }
    }
}
</script>
<style lang="scss" scoped>
@import './style/map.scss';
</style>
<style>
.el-popover {
    min-width: 90px !important;
}

/* 点位弹框样式 */
.content-window-card {
    position: relative;
    box-shadow: none;
    bottom: 0;
    left: 0;
    width: auto;
    padding: 0;
}

.content-window-card p {
    height: 2rem;
}

.custom-info {
    border: solid 1px silver;
}

div.info-top {
    position: relative;
    background: none repeat scroll 0 0 #F9F9F9;
    border-bottom: 1px solid #CCC;
    border-radius: 5px 5px 0 0;
}

div.info-top div {
    display: inline-block;
    color: #333333;
    font-size: 14px;
    font-weight: bold;
    line-height: 31px;
    padding: 0 10px;
}

div.info-top img {
    position: absolute;
    top: 10px;
    right: 10px;
    transition-duration: 0.25s;
}

div.info-top img:hover {
    box-shadow: 0px 0px 5px #000;
}

div.info-middle {
    font-size: 12px;
    padding: 10px 6px;
    line-height: 20px;
}

div.info-bottom {
    height: 0px;
    width: 100%;
    clear: both;
    text-align: center;
}

div.info-bottom img {
    position: relative;
    z-index: 104;
}

.info-middle img {
    float: left;
    margin-right: 6px;
}

.amap-marker-label {
    color: #fff;
    background-color: rgba(255, 255, 255, 0);
    border: solid 2px rgba(100, 255, 200, 0);
    border-radius: 100px;
    cursor: pointer;
}

.el-dialog__body {
    padding: 10px 20px !important;
}

.alert-scroll .scroll-text {
    display: inline-block;
    /* 或者 block，根据布局需要选择 */
    white-space: nowrap;
    /* 防止文本换行 */
    animation: scrollText 20s linear infinite;
    /* 动画名称、持续时间、速度曲线、重复次数 */
}

@keyframes scrollText {
    from {
        transform: translateX(0);
        /* 从右向左滚动 */
    }

    to {
        transform: translateX(-50%);
        /* 完全移出视图范围 */
    }
}

.scroll-container {
    height: 50px;
    line-height: 50px;
}
</style>